package com.ysm.smfu.food;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ysm.smfu.R;
import com.ysm.smfu.StatusBarCompat;
import com.ysm.smfu.adapter.FoodSellerListAdapter;
import com.ysm.smfu.adapter.MyFoodGridAdapter;
import com.ysm.smfu.bean.FoodStore;
import com.ysm.smfu.bean.KeyValueBean;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.food.presenter.FoodMainPersenter;
import com.ysm.smfu.food.presenter.FoodMainPersenterImp;
import com.ysm.smfu.food.view.FoodMainView;
import com.ysm.smfu.map.BasicMapActivity;
import com.ysm.smfu.map.LocationTask;
import com.ysm.smfu.map.OnLocationGetListener;
import com.ysm.smfu.map.PositionEntity;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.view.CustomLoadMoreView;
import com.ysm.smfu.view.MyCycleViewPager;
import com.ysm.smfu.view.popu.ExpandPopTabView;
import com.ysm.smfu.welcome.SharedConfig;
import com.zhy.autolayout.AutoFrameLayout;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class FoodMainFragment extends Fragment implements FoodMainView, View.OnClickListener {
    //搜索背景
    @BindView(R.id.foodMainTopBar)
    AutoFrameLayout foodMainTopBar;

    @BindView(R.id.back)
    ImageView back;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private FoodSellerListAdapter adapter;
    private MyCycleViewPager foodViewPager;
    private SwipeRefreshLayout swipeRefresh;
    private FoodMainPersenter persenterImp;
    private ImageView foodShade;
    private int height;
    private AutoLinearLayout food_viewPager_indicators;
    private TextView accurateAddress;
    private ImageView flushLoc;
    private SharedPreferences sp;
    private ImageView[] imageViews;

    private final String[] categoryNames = {"火锅", "自助餐", "蛋糕甜点", "团购优惠", "西餐", "团购烤肉", "小吃快餐", "其他美食"};
    private final int[] categoryImgs = {R.drawable.huoguo, R.drawable.zizhu, R.drawable.cake, R.drawable.tuangou, R.drawable.xican, R.drawable.kaochuan, R.drawable.xiaochi, R.drawable.othersfood};
    private final String[] ids = {"1", "2", "3", "4", "5", "6", "7", "8"};
    private ExpandPopTabView expandtab_view;
    private int topBarHeight;
    private LinearLayoutManager linearLayoutManager;
    private RotateAnimation rotateAnimation;
    private View animV;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.food_foodsellerslist, null);
        ButterKnife.bind(this, view);
        sp = new SharedConfig(UIUtils.getContext()).getCommoneSp();
        getTopBar();
        persenterImp = new FoodMainPersenterImp(this);
//        显示原始数据
        persenterImp.showOriginalData();
//        加载广告
        persenterImp.loadRecommed();
        initTopBar();
        addToggleButton();//先添加togglebutton显示到页面上，在添加popuwindow布局及数据，防止刚进入时出现空白区域
        persenterImp.addPopuView(getActivity());
        return view;
    }

    /**
     * 获取顶部搜索框
     */
    private void getTopBar() {
        int height = getHeight(foodMainTopBar);
        topBarHeight = height + StatusBarCompat.getStatusBarHeight(getActivity());
    }

    /**
     * 显示初始数据
     */
    @Override
    public void showOriginalPage(List<FoodStore> foodStoreList) {
        swipeRefresh = ((FoodMainActivity) getActivity()).getRefreshLayout();
        initRecyclerView(foodStoreList);
    }

    /**
     * 刷新页面
     *
     * @param foodStoreList
     */
    @Override
    public void flushPage(List<FoodStore> foodStoreList) {
        if (adapter != null) {
            adapter.setNewData(foodStoreList);
            swipeRefresh.setRefreshing(false);
        }
    }

    /**
     * 显示加载更多数据
     *
     * @param foodStoreList
     */
    @Override
    public void loadMorePageSuccess(List<FoodStore> foodStoreList) {
        if (adapter != null) {
            adapter.addData(foodStoreList);
            adapter.loadMoreComplete();
        }
    }

    /**
     * 加载失败
     */
    @Override
    public void loadMorePageFail() {
        adapter.loadMoreFail();
    }

    /**
     * 没有更多数据
     */
    @Override
    public void noMoreData() {
        adapter.loadMoreEnd();
    }

    /**
     * 初始化推荐位
     *
     * @param urls
     */
    @Override
    public void initRecommed(List<String> urls) {
        foodViewPager.setAdapter(new MyPagerAdapter());
        imageViews = UIUtils.initIndicators(3, food_viewPager_indicators, R.drawable.rect_shape, R.drawable.rect_shape_red);
        showCurrLoc();
    }

    /**
     * 添加popupView子条目
     */
    @Override
    public void addItemToPopuView(List<KeyValueBean> smartData, List<KeyValueBean> listAll, List<KeyValueBean> mParentLists, List<ArrayList<KeyValueBean>> mChildrenListLists) {
        expandtab_view.addItemThree(listAll, "全部", "全部");
        expandtab_view.addItemOne(smartData, "智能排序", "智能排序");
        expandtab_view.addItemFour("筛选");
        expandtab_view.addItemTwo(mParentLists, mChildrenListLists, "锦江区", "合江亭", "附近");
    }

    private final String[] toggleButtonName = {"全部", "智能排序", "筛选", "附近"};

    /**
     * 添加toggleButton
     */
    @Override
    public void addToggleButton() {
        expandtab_view.addToggleButton(4, toggleButtonName);
    }

    /**
     * 显示当前位置
     */
    private void showCurrLoc() {
       flushLoc();
    }

    /**
     * 初始化recyclerView
     */
    private void initRecyclerView(List<FoodStore> foodStoreList) {
        initAdapter(foodStoreList);
        linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(adapter);
    }

    /**
     * 移动到指定位置
     */
    public void moveToPosition() {
        linearLayoutManager.scrollToPositionWithOffset(1, 400);
        linearLayoutManager.setStackFromEnd(true);
    }

    /**
     * 初始化adapter
     */
    private void initAdapter(List<FoodStore> foodStoreList) {
        adapter = new FoodSellerListAdapter(foodStoreList);
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.activity_food_main_header, null);
        adapter.addHeaderView(view, 0);
        adapter.setLoadMoreView(new CustomLoadMoreView());
//        自定义加载更多
        initView(view);
        initListener();
    }

    private void initView(View view) {
//        条件选择
        initPopuTabView(view);
        foodViewPager = (MyCycleViewPager) view.findViewById(R.id.food_viewPager);
        AutoRelativeLayout food_tuijian = (AutoRelativeLayout) view.findViewById(R.id.food_tuijian);
//        遮罩
        foodShade = (ImageView) view.findViewById(R.id.foodShade);
//        刷新位置
        flushLoc = (ImageView) view.findViewById(R.id.flushLoc);
//        精确位置
        accurateAddress = (TextView) view.findViewById(R.id.accurateAddress);
//        指示点
        food_viewPager_indicators = (AutoLinearLayout) view.findViewById(R.id.food_viewPager_indicators);

        GridView gridView = (GridView) view.findViewById(R.id.gridView);
        MyFoodGridAdapter adapter = new MyFoodGridAdapter(categoryNames, categoryImgs, ids, getActivity());
        gridView.setAdapter(adapter);
    }

    /**
     * 创建条件选择器
     *
     * @param view
     */
    private void initPopuTabView(View view) {
        expandtab_view = (ExpandPopTabView) view.findViewById(R.id.expandtab_view);
        expandtab_view.setTopBarHeight(topBarHeight);
//        expandtab_view.setRecyclerView(this);
    }

    private void initListener() {
        back.setOnClickListener(this);
        foodMainTopBar.setOnClickListener(this);
        flushLoc.setOnClickListener(this);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                共享动画
                ImageView img = (ImageView) view.findViewById(R.id.img);
                UIUtils.startActivity(FoodDetailActivity.class);
            }
        });

        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (adapter.getItemCount() > 10)
                    persenterImp.loadMoreData();
            }
        }, recyclerView);

        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                persenterImp.flushData();
            }
        });

        foodViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                for (int i = 0; i < imageViews.length; i++) {
                    if (i == position % imageViews.length)
                        imageViews[i].setBackgroundResource(R.drawable.rect_shape_red);
                    else
                        imageViews[i].setBackgroundResource(R.drawable.rect_shape);
                }
            }
        });
    }

    @OnClick({R.id.map})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.flushLoc://刷新位置
                animV = v;
                doAnimator(v);
                flushLoc();
                break;
            case R.id.foodMainTopBar:
                UIUtils.startActivity(FoodCategoryActivity.class);
                expandtab_view.onDismissForOther();
                break;
            case R.id.map://打开地图
                UIUtils.startActivity(BasicMapActivity.class);
                break;
            case R.id.back:
                getActivity().finish();
                break;
        }
    }

    /**
     * 开始定位
     */
    private void flushLoc() {
        final LocationTask locationTask = LocationTask.getInstance();
        locationTask.setOnLocationGetListener(new OnLocationGetListener() {
            @Override
            public void onLocationGet(PositionEntity entity) {
                if (entity != null)
                    accurateAddress.setText(String.format(UIUtils.getString(R.string.currentLoc), entity.address));
                else
                    accurateAddress.setText("定位失败");
                stopAnim();
                locationTask.stopLocate();
            }

            @Override
            public void onRegecodeGet(PositionEntity entity) {
            }
        });
        locationTask.startSingleLocate();
    }

    /**
     * 做刷新动画
     *
     * @param v
     */
    private void doAnimator(View v) {
        if (rotateAnimation == null) {
            rotateAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            rotateAnimation.setDuration(1000);
            rotateAnimation.setRepeatCount(Animation.INFINITE);
        }
        v.startAnimation(rotateAnimation);
    }

    /**
     * 停止动画
     */
    private void stopAnim() {
        if (rotateAnimation != null) {
            rotateAnimation.cancel();
            animV.clearAnimation();
        }
    }

    /**
     * 推荐位ViewPager的Adapter
     */
    private class MyPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
//            return aphotos == null ? 0 : aphotos.length > 1 ? Integer.MAX_VALUE : aphotos.length;
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = LayoutInflater.from(UIUtils.getContext()).inflate(R.layout.imageview, null);
            ImageView imageView = (ImageView) view.findViewById(R.id.img);
            imageView.setImageResource(R.drawable.food_tuijian);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }


    private int disY = 0;

    /**
     * 初始化搜索栏背景变化
     */
    private void initTopBar() {
        height = getHeight(foodShade);
        final int statusBarHeight = StatusBarCompat.getStatusBarHeight(getActivity());
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                disY += dy;
                if (disY > height - statusBarHeight) {
                    foodMainTopBar.setBackgroundColor(getResources().getColor(R.color.green));
                } else {
                    foodMainTopBar.setBackgroundColor(getResources().getColor(R.color.translate));
                }
            }
        });
    }

    /**
     * 获取view高度
     *
     * @param view
     * @return
     */
    private int getHeight(View view) {
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(w, h);
        return view.getMeasuredHeight();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}
